{% extends 'base.html' %}
{% load static %}

{% block title %}{{ product.name }} - 商城系统{% endblock %}

{% block extra_css %}
<style>
    .product-main-img {
        max-height: 450px;
        max-width: 100%;
        object-fit: contain;
        display: block;
        margin: 0 auto;
    }
    
    .thumbnail-img {
        height: 80px;
        width: 100%;
        object-fit: contain;
        cursor: pointer;
        border: 1px solid #dee2e6;
        padding: 5px;
    }
    
    .thumbnail-img.active {
        border-color: #007bff;
    }
    
    .price {
        font-size: 1.8rem;
        color: #e74c3c;
        font-weight: bold;
    }
    
    .original-price {
        font-size: 1.2rem;
        color: #95a5a6;
        text-decoration: line-through;
        margin-left: 10px;
    }
    
    .discount-tag {
        background-color: #e74c3c;
        color: white;
        font-size: 0.9rem;
        padding: 2px 6px;
        border-radius: 4px;
        margin-left: 10px;
    }
    
    .product-action {
        background-color: #f8f9fa;
        padding: 20px;
        border-radius: 5px;
    }
    
    .quantity-control {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
    }
    
    .quantity-control .btn {
        width: 40px;
        height: 40px;
        font-size: 1.2rem;
        padding: 0;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
    .quantity-control input {
        width: 60px;
        height: 40px;
        text-align: center;
        font-size: 1.2rem;
        border-left: 0;
        border-right: 0;
        border-radius: 0;
    }
    
    .related-product-img {
        height: 150px;
        object-fit: contain;
    }
    
    .product-description {
        white-space: pre-line;
    }
    
    /* 商品描述中的HTML元素样式 */
    .product-description br {
        display: block;
        margin: 5px 0;
    }
    
    .product-description ul, 
    .product-description ol {
        padding-left: 20px;
        margin: 10px 0;
    }
    
    .product-description li {
        margin-bottom: 5px;
    }
    
    .store-info {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
    }
    
    .store-info .store-icon {
        width: 50px;
        height: 50px;
        background-color: #e1e1e1;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;
        font-size: 1.5rem;
    }
    
    .store-info .store-name {
        font-weight: bold;
    }
    
    .self-operated {
        color: #e74c3c;
        font-size: 0.9rem;
    }
    
    .comment-avatar {
        width: 50px;
        height: 50px;
        border-radius: 50%;
    }
    
    .rating {
        color: #f39c12;
    }
    
    .comment-images {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-top: 10px;
    }
    
    .comment-images img {
        width: 80px;
        height: 80px;
        object-fit: cover;
        border-radius: 5px;
        cursor: pointer;
    }

    /* 新增样式 - 固定右侧内容 */
    .product-info-sticky {
        position: sticky;
        top: 20px;
    }
    
    /* 新增样式 - 轮播图片 */
    .product-images-carousel {
        margin-bottom: 1rem;
    }
    
    .carousel-item img {
        max-height: 450px;
        width: auto;
        margin: 0 auto;
        object-fit: contain;
    }
    
    /* 商品详情图片区域 */
    .product-detail-images-gallery img {
        max-width: 100%;
        height: auto;
        margin-bottom: 0;
        display: block;
    }
    
    .product-detail-images-gallery {
        display: flex;
        flex-direction: column;
        line-height: 0;
    }

    /* 新样式 - 商品详情选项卡取消上边框 */
    .product-tabs {
        border-top: none;
    }
    
    /* 新样式 - 整体内容区域 */
    .product-content-wrapper {
        display: flex;
        flex-wrap: wrap;
    }
    
    .product-left-column {
        flex: 0 0 100%;
    }
    
    .product-right-column {
        flex: 0 0 100%;
    }
    
    /* 响应式调整 */
    @media (min-width: 992px) {
        .product-left-column {
            flex: 0 0 60%;
            max-width: 60%;
            padding-right: 20px;
        }
        
        .product-right-column {
            flex: 0 0 40%;
            max-width: 40%;
        }
        
        .product-info-sticky {
            position: sticky;
            top: 20px;
        }
    }
    
    @media (max-width: 991px) {
        .product-info-sticky {
            position: static;
            margin-bottom: 30px;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="container mt-4">
    <!-- 面包屑导航 -->
    <nav aria-label="breadcrumb" class="mb-4">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="{% url 'index' %}">首页</a></li>
            <li class="breadcrumb-item"><a href="{% url 'category' product.product_type.subcategory.category.id %}">{{ product.product_type.subcategory.category.name }}</a></li>
            <li class="breadcrumb-item"><a href="{% url 'subcategory' product.product_type.subcategory.id %}">{{ product.product_type.subcategory.name }}</a></li>
            <li class="breadcrumb-item active" aria-current="page">{{ product.name }}</li>
        </ol>
    </nav>
    
    <div class="product-content-wrapper">
        <!-- 左侧区域：商品图片 + 商品详情 -->
        <div class="product-left-column">
            <!-- 商品轮播图 -->
            <div id="productImagesCarousel" class="carousel slide product-images-carousel" data-bs-ride="carousel">
                <div class="carousel-inner">
                    <div class="carousel-item active">
                        <img src="" data-src="{{ product.get_main_image_url }}" class="d-block w-100 lazy-load" alt="{{ product.name }}">
                    </div>
                    {% if product.detail_images %}
                        {% for img in product.detail_images %}
                            {% if img and 'http' in img or '/' in img %}
                            <div class="carousel-item">
                                <img src="" data-src="{{ img }}" class="d-block w-100 lazy-load" alt="{{ product.name }}">
                            </div>
                            {% endif %}
                        {% endfor %}
                    {% endif %}
                </div>
                <button class="carousel-control-prev" type="button" data-bs-target="#productImagesCarousel" data-bs-slide="prev">
                    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                    <span class="visually-hidden">上一张</span>
                </button>
                <button class="carousel-control-next" type="button" data-bs-target="#productImagesCarousel" data-bs-slide="next">
                    <span class="carousel-control-next-icon" aria-hidden="true"></span>
                    <span class="visually-hidden">下一张</span>
                </button>
            </div>
            
            <!-- 图片缩略图 -->
            {% if product.detail_images %}
            <div class="row mt-3 justify-content-center mb-4">
                <div class="col-2 col-sm-2 col-md-2 px-1">
                    <img src="" data-src="{{ product.get_main_image_url }}" class="thumbnail-img active lazy-load" 
                         data-bs-target="#productImagesCarousel" data-bs-slide-to="0" alt="{{ product.name }}">
                </div>
                {% for img in product.detail_images %}
                {% if img and 'http' in img or '/' in img %}
                <div class="col-2 col-sm-2 col-md-2 px-1">
                    <img src="" data-src="{{ img }}" class="thumbnail-img lazy-load" 
                         data-bs-target="#productImagesCarousel" data-bs-slide-to="{{ forloop.counter }}" alt="{{ product.name }}">
                </div>
                {% endif %}
                {% endfor %}
            </div>
            {% endif %}
            
            <!-- 直接放置商品详情在主图下方 -->
            <div class="mt-4 mb-5">
                <h4 class="border-bottom pb-2 mb-3" id="product-full-description">商品详情</h4>
                {% if parsed_detail_images %}
                    <div class="product-detail-images-gallery">
                        {% for image_path in parsed_detail_images %}
                                <img src="" data-src="{% static image_path %}" class="img-fluid lazy-load" alt="商品详情图 {{ forloop.counter }}">
                        {% endfor %}
                    </div>
                {% elif product.description %}
                <h5>商品描述</h5>
                <div class="product-description">{{ product.description|safe }}</div>
                {% else %}
                    <p class="mt-4">暂无更多商品详情信息。</p>
                {% endif %}
            </div>
            
            <!-- 用户评价 -->
            <div class="mt-4 mb-5 deferred-load">
                <h4 class="border-bottom pb-2 mb-3">用户评价 ({{ comments.count }})</h4>
                {% if comments %}
                <div class="comments-list">
                    {% for comment in comments %}
                    <div class="card mb-3">
                        <div class="card-body">
                            <div class="d-flex mb-3">
                                <img src="" data-src="https://randomuser.me/api/portraits/{% cycle 'men' 'women' %}/{{ forloop.counter|add:10 }}.jpg" class="comment-avatar me-3 lazy-load" alt="用户头像">
                                <div>
                                    <h5 class="mb-0">{{ comment.user.username }}</h5>
                                    <div class="rating">
                                        {% for i in "12345" %}
                                        {% if forloop.counter <= comment.rating %}
                                        <i class="bi bi-star-fill"></i>
                                        {% else %}
                                        <i class="bi bi-star"></i>
                                        {% endif %}
                                        {% endfor %}
                                    </div>
                                    <small class="text-muted">{{ comment.created_time|date:"Y-m-d H:i" }}</small>
                                </div>
                            </div>
                            <p>{{ comment.content }}</p>
                            {% if comment.images %}
                            <div class="comment-images">
                                {% for img in comment.images %}
                                <img src="" data-src="{{ img }}" class="lazy-load" alt="评价图片">
                                {% endfor %}
                            </div>
                            {% endif %}
                        </div>
                    </div>
                    {% endfor %}
                </div>
                {% else %}
                <div class="alert alert-info">
                    暂无评价，购买后可以添加评价
                </div>
                {% endif %}
            </div>
            
            <!-- 相关商品推荐 -->
            {% if related_products %}
            <div class="mb-5 deferred-load">
                <h4 class="border-bottom pb-2 mb-3">相关商品推荐</h4>
                <div class="row">
                    {% for related in related_products %}
                    <div class="col-md-4 col-sm-6 col-6 mb-3">
                        <div class="card h-100">
                            <img src="" data-src="{{ related.get_main_image_url }}" class="card-img-top related-product-img lazy-load" alt="{{ related.name }}">
                            <div class="card-body p-2">
                                <h6 class="card-title mb-1">{{ related.name|truncatechars:20 }}</h6>
                                <p class="price mb-0">¥{{ related.price }}</p>
                            </div>
                            <div class="card-footer p-2 bg-white">
                                <a href="{% url 'product_detail' related.id %}" class="btn btn-sm btn-outline-primary w-100">查看详情</a>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
            {% endif %}
        </div>
        
        <!-- 右侧商品信息 - 使用粘性定位 -->
        <div class="product-right-column">
            <div class="product-info-sticky">
                <h1 class="mb-3">{{ product.name }}</h1>
                
                <!-- 店铺信息 -->
                <div class="store-info">
                    <div class="store-icon">
                        <i class="bi bi-shop"></i>
                    </div>
                    <div>
                        <div class="store-name">{{ product.store_name }}</div>
                        {% if product.is_self_operated %}
                        <div class="self-operated">自营</div>
                        {% endif %}
                    </div>
                </div>
                
                <!-- 价格信息 -->
                <div class="mb-4">
                    <span class="price">¥{{ product.price }}</span>
                    {% if product.original_price and product.original_price > product.price %}
                    <span class="original-price">¥{{ product.original_price }}</span>
                    <span class="discount-tag">{{ product.discount_rate }}% 折扣</span>
                    {% endif %}
                </div>
                
                <!-- 库存信息 -->
                <div class="mb-3">
                    <h5>库存状态：</h5>
                    {% if product.stock > 0 %}
                        <span class="badge bg-success">有货</span>
                        {% if product.stock < 10 %}
                            <span class="text-danger ms-2">库存紧张，抓紧下单！</span>
                        {% endif %}
                    {% else %}
                        <span class="badge bg-danger">已售罄</span>
                        <span class="text-muted ms-2">该商品暂时缺货，您可以先收藏或查看其他商品</span>
                    {% endif %}
                </div>
                
                <!-- 商品简介 -->
                {% if product.description %}
                <div class="mb-4">
                    <h5>商品简介：</h5>
                    <p class="product-description">{{ product.description|truncatechars:200|safe }}</p>
                    {% if product.description|length > 200 %}
                    <div class="text-end">
                        <a href="#product-full-description" class="text-decoration-none">查看完整描述</a>
                    </div>
                    {% endif %}
                </div>
                {% endif %}
                
                <!-- 购买区域 -->
                <div class="product-action">
                    <div class="quantity-control">
                        <button class="btn btn-outline-secondary" onclick="decreaseQuantity()" {% if product.stock <= 0 %}disabled{% endif %}>-</button>
                        <input type="text" class="form-control" id="quantity" value="1" {% if product.stock <= 0 %}disabled{% endif %}>
                        <button class="btn btn-outline-secondary" onclick="increaseQuantity()" {% if product.stock <= 0 %}disabled{% endif %}>+</button>
                    </div>
                    
                    <div class="row">
                        <div class="col-6">
                            <form id="add-to-cart-form" method="post" action="{% url 'add_to_cart' product.id %}">
                                {% csrf_token %}
                                <input type="hidden" name="quantity" id="cart-quantity" value="1">
                                <input type="hidden" name="next" value="{{ request.path }}">
                                <button type="button" id="add-to-cart-btn" class="btn btn-primary w-100" {% if in_cart or product.stock <= 0 %}disabled{% endif %}>
                                    <i class="bi bi-cart-plus"></i> 
                                    {% if in_cart %}
                                        已在购物车
                                    {% elif product.stock <= 0 %}
                                        缺货
                                    {% else %}
                                        加入购物车
                                    {% endif %}
                                </button>
                            </form>
                        </div>
                        <div class="col-6">
                            {% if user.is_authenticated %}
                            <form method="post" action="{% url 'checkout' %}">
                                {% csrf_token %}
                                <input type="hidden" name="product_id" value="{{ product.id }}">
                                <input type="hidden" name="quantity" id="buy-now-quantity" value="1">
                                <input type="hidden" name="buy_now" value="true">
                                <button type="submit" class="btn btn-danger w-100" {% if product.stock <= 0 %}disabled{% endif %}>
                                    <i class="bi bi-lightning-fill"></i> 
                                    {% if product.stock <= 0 %}
                                        缺货
                                    {% else %}
                                        立即购买
                                    {% endif %}
                                </button>
                            </form>
                            {% else %}
                            <a href="{% url 'login' %}?next={{ request.path }}" class="btn btn-danger w-100">
                                <i class="bi bi-lightning-fill"></i> 立即购买
                            </a>
                            {% endif %}
                        </div>
                    </div>
                </div>
                
                <!-- 服务保障 -->
                <div class="mt-4">
                    <h5>服务保障：</h5>
                    <div class="d-flex flex-wrap">
                        <span class="badge bg-light text-dark me-2 mb-2 p-2">
                            <i class="bi bi-shield-check text-success"></i> 正品保障
                        </span>
                        <span class="badge bg-light text-dark me-2 mb-2 p-2">
                            <i class="bi bi-truck text-primary"></i> 闪电发货
                        </span>
                        <span class="badge bg-light text-dark me-2 mb-2 p-2">
                            <i class="bi bi-arrow-counterclockwise text-warning"></i> 7天无理由退换
                        </span>
                        <span class="badge bg-light text-dark me-2 mb-2 p-2">
                            <i class="bi bi-headset text-info"></i> 24小时客服
                        </span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    // 页面加载完成后执行
    document.addEventListener('DOMContentLoaded', function() {
        // 优先加载主图
        const mainImage = document.querySelector('.carousel-item.active img.lazy-load');
        if (mainImage && mainImage.dataset.src) {
            const img = new Image();
            img.onload = function() {
                mainImage.src = mainImage.dataset.src;
                mainImage.classList.add('loaded');
            };
            img.src = mainImage.dataset.src;
        }
        
        // 延迟初始化其他交互功能
        setTimeout(setupInteractions, 100);
    });
    
    // 设置所有交互功能
    function setupInteractions() {
        // 数量控制
        setupQuantityControl();
        
        // 缩略图点击事件
        setupThumbnailEvents();
        
        // 同步购物车和立即购买数量
        document.getElementById('quantity').addEventListener('change', function() {
            document.getElementById('cart-quantity').value = this.value;
            document.getElementById('buy-now-quantity').value = this.value;
        });
        
        // 加入购物车AJAX操作
        setupAddToCartAjax();
    }
    
    // 加入购物车AJAX
    function setupAddToCartAjax() {
        const addToCartBtn = document.getElementById('add-to-cart-btn');
        if (!addToCartBtn) return;
        
        addToCartBtn.addEventListener('click', function() {
            // 如果按钮已禁用，不执行操作
            if (this.disabled) return;
            
            const form = document.getElementById('add-to-cart-form');
            const formData = new FormData(form);
            const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
            
            // 显示加载状态
            const originalText = this.innerHTML;
            this.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 处理中...';
            this.disabled = true;
            
            fetch(form.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': csrfToken,
                    'X-Requested-With': 'XMLHttpRequest'
                },
                credentials: 'same-origin'
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应异常');
                }
                return response.json();
            })
            .then(data => {
                // 处理成功响应
                if (data.success) {
                    // 显示成功消息
                    if (typeof showToast === 'function') {
                        showToast(data.message || '已成功添加到购物车', 'success');
                    }
                    
                    // 更新购物车图标数量
                    updateCartCount(data.cart_count);
                    
                    // 更新按钮状态为"已在购物车"
                    this.innerHTML = '<i class="bi bi-cart-check"></i> 已在购物车';
                    this.disabled = true;
                } else {
                    // 检查是否需要登录
                    if (data.redirect_url && data.message === '请先登录') {
                        // 跳转到登录页面
                        window.location.href = data.redirect_url;
                        return;
                    }
                    
                    // 显示错误消息
                    if (typeof showToast === 'function') {
                        showToast(data.message || '添加失败', 'danger');
                    }
                    this.innerHTML = originalText;
                    this.disabled = false;
                }
            })
            .catch(error => {
                console.error('添加购物车出错:', error);
                // 显示错误消息
                if (typeof showToast === 'function') {
                    showToast('添加购物车失败，请稍后重试', 'danger');
                }
                this.innerHTML = originalText;
                this.disabled = false;
            });
        });
    }
    
    // 更新购物车图标数量
    function updateCartCount(count) {
        const cartCountElem = document.getElementById('cart-count');
        if (cartCountElem) {
            if (count > 0) {
                cartCountElem.textContent = count;
                cartCountElem.style.display = 'inline';
            } else {
                cartCountElem.textContent = '';
                cartCountElem.style.display = 'none';
            }
        }
    }
    
    // 数量控制函数
    function setupQuantityControl() {
        function decreaseQuantity() {
            var quantity = document.getElementById('quantity');
            var cartQuantity = document.getElementById('cart-quantity');
            var buyNowQuantity = document.getElementById('buy-now-quantity');
            var value = parseInt(quantity.value);
            if (value > 1) {
                quantity.value = value - 1;
                cartQuantity.value = value - 1;
                buyNowQuantity.value = value - 1;
            }
        }
        
        function increaseQuantity() {
            var quantity = document.getElementById('quantity');
            var cartQuantity = document.getElementById('cart-quantity');
            var buyNowQuantity = document.getElementById('buy-now-quantity');
            var value = parseInt(quantity.value);
            quantity.value = value + 1;
            cartQuantity.value = value + 1;
            buyNowQuantity.value = value + 1;
        }
        
        // 为减少按钮添加事件
        const decreaseBtn = document.querySelector('.btn[onclick="decreaseQuantity()"]');
        if (decreaseBtn) {
            decreaseBtn.removeAttribute('onclick');
            decreaseBtn.addEventListener('click', decreaseQuantity);
        }
        
        // 为增加按钮添加事件
        const increaseBtn = document.querySelector('.btn[onclick="increaseQuantity()"]');
        if (increaseBtn) {
            increaseBtn.removeAttribute('onclick');
            increaseBtn.addEventListener('click', increaseQuantity);
        }
    }

    // 缩略图点击事件
    function setupThumbnailEvents() {
        const thumbnails = document.querySelectorAll('.thumbnail-img');
        if (thumbnails.length === 0) return;
        
        thumbnails.forEach(function(thumb) {
            thumb.addEventListener('click', function() {
                // 更新激活状态
                thumbnails.forEach(img => {
                    img.classList.remove('active');
                });
                this.classList.add('active');
                
                // 切换轮播图到对应索引
                var slideIndex = this.getAttribute('data-bs-slide-to');
                var carousel = bootstrap.Carousel.getInstance(document.getElementById('productImagesCarousel'));
                if (!carousel) {
                    carousel = new bootstrap.Carousel(document.getElementById('productImagesCarousel'));
                }
                carousel.to(parseInt(slideIndex));
                
                // 确保目标图片已加载
                const targetImage = document.querySelector(`.carousel-item:nth-child(${parseInt(slideIndex) + 1}) img.lazy-load`);
                if (targetImage && targetImage.dataset.src && targetImage.src !== targetImage.dataset.src) {
                    targetImage.src = targetImage.dataset.src;
                    targetImage.classList.add('loaded');
                }
            });
        });
    }

    // 轮播图事件，更新缩略图激活状态
    document.getElementById('productImagesCarousel').addEventListener('slid.bs.carousel', function(event) {
        var activeIndex = event.to;
        thumbnails.forEach((thumb, index) => {
            if (index === activeIndex) {
                thumb.classList.add('active');
            } else {
                thumb.classList.remove('active');
            }
        });
        
        // 预加载下一张图片
        const nextIndex = (activeIndex + 1) % document.querySelectorAll('.carousel-item').length;
        const nextImage = document.querySelector(`.carousel-item:nth-child(${nextIndex + 1}) img.lazy-load`);
        if (nextImage && nextImage.dataset.src && nextImage.src !== nextImage.dataset.src) {
            const img = new Image();
            img.src = nextImage.dataset.src;
        }
    });
</script>
{% endblock %} 